package com.ozner.cup.Chat.EaseUI.widget.chartrow;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.ozner.cup.Chat.EaseUI.Adapter.EaseMessageAdapter;
import com.ozner.cup.Chat.EaseUI.model.MessageDirect;
import com.ozner.cup.Chat.EaseUI.widget.EaseChatMessageList;
import com.ozner.cup.Command.OznerPreference;
import com.ozner.cup.DBHelper.DBManager;
import com.ozner.cup.DBHelper.EMMessage;
import com.ozner.cup.DBHelper.UserInfo;
import com.ozner.cup.R;
import com.ozner.cup.Utils.DateUtils;

import java.util.Date;

public abstract class EaseChatRow extends LinearLayout {
    protected static final String TAG = EaseChatRow.class.getSimpleName();

    protected LayoutInflater inflater;
    protected Context context;
    protected BaseAdapter adapter;
    protected EMMessage message;
    protected int position;
    private String headImgUrl = "";

    protected TextView timeStampView;
    protected ImageView userAvatarView;
    protected View bubbleLayout;
//    protected TextView usernickView;

    protected TextView percentageView;
    protected ProgressBar progressBar;
    protected ImageView statusView;
    protected Activity activity;

    protected TextView ackedView;
    protected TextView deliveredView;
//
//    protected EMCallBack messageSendCallback;
//    protected EMCallBack messageReceiveCallback;

    protected EaseChatMessageList.MessageListItemClickListener itemClickListener;

    public EaseChatRow(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context);
        this.context = context;
        this.activity = (Activity) context;
        this.message = message;
        this.position = position;
        this.adapter = adapter;
        inflater = LayoutInflater.from(context);
        UserInfo userInfo = DBManager.getInstance(context).getUserInfo(OznerPreference.GetValue(context, OznerPreference.UserId, null));
        headImgUrl = userInfo.getHeadimg();
        initView();
    }

    private void initView() {
        onInflateView();
        timeStampView = (TextView) findViewById(R.id.timestamp);
        userAvatarView = (ImageView) findViewById(R.id.iv_userhead);
        bubbleLayout = findViewById(R.id.bubble);
//        usernickView = (TextView) findViewById(R.id.tv_userid);

        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        statusView = (ImageView) findViewById(R.id.msg_status);
        ackedView = (TextView) findViewById(R.id.tv_ack);
        deliveredView = (TextView) findViewById(R.id.tv_delivered);

        onFindViewById();
    }

    /**
     * set property according message and postion
     *
     * @param message
     * @param position
     */
    public void setUpView(EMMessage message, int position,
                          EaseChatMessageList.MessageListItemClickListener itemClickListener) {
        this.message = message;
        this.position = position;
        this.itemClickListener = itemClickListener;

        setUpBaseView();
        onSetUpView();
        setClickListener();
    }

    private void setUpBaseView() {
        // set nickname, avatar and background of bubble
        //显示时间戳
        TextView timestamp = (TextView) findViewById(R.id.timestamp);
        if (timestamp != null) {
            if (position == 0) {
                timestamp.setText(DateUtils.hourMinFormt(new Date(message.getTime())));
                timestamp.setVisibility(View.VISIBLE);
            } else {
                // show time stamp if interval with last message is > 30 seconds
                EMMessage prevMessage = (EMMessage) adapter.getItem(position - 1);
                if (prevMessage != null && DateUtils.isCloseEnough(prevMessage.getTime(), message.getTime())) {
                    timestamp.setVisibility(View.GONE);
                } else {
                    timestamp.setText(DateUtils.hourMinFormt(new Date(message.getTime())));
                    timestamp.setVisibility(View.VISIBLE);
                }
            }
        }


        //set nickname and avatar
        // TODO: 2016/12/12 设置头像和昵称
//        if(message.getMDirect() == MessageDirect.SEND){
//            EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
//        }else{
//            EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);
//            EaseUserUtils.setUserNick(message.getFrom(), usernickView);
//        }

        if (message.getMDirect() == MessageDirect.SEND) {
            Glide.with(context).load(headImgUrl).asBitmap().placeholder(R.drawable.customer).centerCrop().into(new BitmapImageViewTarget(userAvatarView) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    userAvatarView.setImageDrawable(circularBitmapDrawable);
                }
            });
        }
//        else {
//            Glide.with(context).load(headImgUrl).asBitmap().placeholder(R.drawable.ozner).centerCrop().into(new BitmapImageViewTarget(userAvatarView) {
//                @Override
//                protected void setResource(Bitmap resource) {
//                    RoundedBitmapDrawable circularBitmapDrawable =
//                            RoundedBitmapDrawableFactory.create(context.getResources(), resource);
//                    circularBitmapDrawable.setCircular(true);
//                    userAvatarView.setImageDrawable(circularBitmapDrawable);
//                }
//            });
//        }

//        if(deliveredView != null){
//            if (message.isDelivered()) {
//                deliveredView.setVisibility(View.VISIBLE);
//            } else {
//                deliveredView.setVisibility(View.INVISIBLE);
//            }
//        }

//        if(ackedView != null){
//            if (message.isAcked()) {
//                if (deliveredView != null) {
//                    deliveredView.setVisibility(View.INVISIBLE);
//                }
//                ackedView.setVisibility(View.VISIBLE);
//            } else {
//                ackedView.setVisibility(View.INVISIBLE);
//            }
//        }


        if (adapter instanceof EaseMessageAdapter) {
            if (((EaseMessageAdapter) adapter).isShowAvatar())
                userAvatarView.setVisibility(View.VISIBLE);
            else
                userAvatarView.setVisibility(View.GONE);
//            if (usernickView != null) {
//                if (((EaseMessageAdapter) adapter).isShowUserNick())
//                    usernickView.setVisibility(View.VISIBLE);
//                else
//                    usernickView.setVisibility(View.GONE);
//            }
            if (message.getMDirect() == MessageDirect.SEND) {
                if (((EaseMessageAdapter) adapter).getMyBubbleBg() != null) {
                    bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getMyBubbleBg());
                }
            } else if (message.getMDirect() == MessageDirect.RECEIVE) {
                if (((EaseMessageAdapter) adapter).getOtherBuddleBg() != null) {
                    bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getOtherBuddleBg());
                }
            }
        }
    }

    /**
     * set callback for sending message
     */
    protected void setMessageSendCallback() {
//        if(messageSendCallback == null){
//            messageSendCallback = new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//                    updateView();
//                }
//
//                @Override
//                public void onProgress(final int progress, String status) {
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if(percentageView != null)
//                                percentageView.setText(progress + "%");
//
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, String error) {
//                    updateView();
//                }
//            };
//        }
//        message.setMessageStatusCallback(messageSendCallback);
    }

    /**
     * set callback for receiving message
     */
    protected void setMessageReceiveCallback() {
//        if(messageReceiveCallback == null){
//            messageReceiveCallback = new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//                    updateView();
//                }
//
//                @Override
//                public void onProgress(final int progress, String status) {
//                    activity.runOnUiThread(new Runnable() {
//                        public void run() {
//                            if(percentageView != null){
//                                percentageView.setText(progress + "%");
//                            }
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, String error) {
//                    updateView();
//                }
//            };
//        }
//        message.setMessageStatusCallback(messageReceiveCallback);
    }


    private void setClickListener() {
        if (bubbleLayout != null) {
            bubbleLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        if (!itemClickListener.onBubbleClick(message)) {
                            // if listener return false, we call default handling
                            onBubbleClick();
                        }
                    }
                }
            });

            bubbleLayout.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onBubbleLongClick(message);
                    }
                    return true;
                }
            });
        }

        if (statusView != null) {
            statusView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onResendClick(message);
                    }
                }
            });
        }

//        if(userAvatarView != null){
//            userAvatarView.setOnClickListener(new OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    if (itemClickListener != null) {
//                        if (message.direct() == MessageDirect.SEND) {
//                            itemClickListener.onUserAvatarClick(EMClient.getInstance().getCurrentUser());
//                        } else {
//                            itemClickListener.onUserAvatarClick(message.getFrom());
//                        }
//                    }
//                }
//            });
//            userAvatarView.setOnLongClickListener(new OnLongClickListener() {
//
//                @Override
//                public boolean onLongClick(View v) {
//                    if(itemClickListener != null){
//                        if (message.direct() == MessageDirect.SEND) {
//                            itemClickListener.onUserAvatarLongClick(EMClient.getInstance().getCurrentUser());
//                        } else {
//                            itemClickListener.onUserAvatarLongClick(message.getFrom());
//                        }
//                        return true;
//                    }
//                    return false;
//                }
//            });
//        }
    }


    protected void updateView() {
//        activity.runOnUiThread(new Runnable() {
//            public void run() {
//                if (message.status() == EMMessage.Status.FAIL) {
//
//                    if (message.getError() == EMError.MESSAGE_INCLUDE_ILLEGAL_CONTENT) {
//                        Toast.makeText(activity,activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_invalid_content), Toast.LENGTH_SHORT).show();
//                    } else if (message.getError() == EMError.GROUP_NOT_JOINED) {
//                        Toast.makeText(activity,activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_not_in_the_group), Toast.LENGTH_SHORT).show();
//                    } else {
//                        Toast.makeText(activity,activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT).show();
//                    }
//                }
//
//                onUpdateView();
//            }
//        });

    }

    protected abstract void onInflateView();

    /**
     * find view by id
     */
    protected abstract void onFindViewById();

    /**
     * refresh list view when message status change
     */
    protected abstract void onUpdateView();

    /**
     * setup view
     */
    protected abstract void onSetUpView();

    /**
     * on bubble clicked
     */
    protected abstract void onBubbleClick();

}
